package com.hankol.winecellar

import android.graphics.Typeface
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.activity.BaseLazyFragment
import com.baselibrary.extension.checkNotNull
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.ARouterUtils
import com.baselibrary.utils.DoubleClickHelper
import com.baselibrary.utils.SpUtils
import com.google.android.material.tabs.TabLayout
import com.hankol.winecellar.databinding.ActivityGoodsManagerBinding
import com.hankol.winecellar.fragment.GoodsManagerListFragment
import com.hankol.winecellar.view.MyOrderTabVp
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**新零售二期-商品管理
 * @author: merbng
 * @time: 2022/8/23 12:53
 * @description:
 */
@Route(path = ActivityRouter.WINE_CELLAR.GOODS_MANAGER)
class GoodsManagerActivity : BaseActivity(), View.OnClickListener {
    private lateinit var dataBinding: ActivityGoodsManagerBinding
    private lateinit var viewModel: WineCellarViewModel
    private val pagerAdapter: MyOrderTabVp by lazy { MyOrderTabVp(supportFragmentManager) }

    private var fragmentList: ArrayList<BaseLazyFragment> = arrayListOf(GoodsManagerListFragment.newInstance(0), GoodsManagerListFragment.newInstance(1))

    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_goods_manager
    }

    override fun init() {
        setStatusBarHeight(R.color.color_F9F9F9)
        dataBinding = getDataBinding<ActivityGoodsManagerBinding>()
        viewModel = getActivityViewModelProvider(this).get(WineCellarViewModel::class.java)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initListener()
        initObserver()
        //顶部提示
        val isCloseTip = SpUtils.getBoolean(this, Constants.KEY_GOODS_MANAGER_TIP_IS_CLOSE, false)
        dataBinding.llGoodsManagerTip.visibility = if (isCloseTip) View.GONE else View.VISIBLE

        viewModel.reqGoodsNumStatistics(SpUtils.getInstance().currentWineryInfo.dealerCode)
    }

    private fun initObserver() {
        viewModel.goodsNumStatisticsLD.observe(this, Observer {
            if(it.checkNotNull()) {
                var tabList = mutableListOf<String>("售卖中 ${if (it.onLineNum > 0) "${it.onLineNum}" else ""}", "已下架 ${if (it.offLineNum > 0) "${it.offLineNum}" else ""}")
                pagerAdapter.setTitleList(tabList)
                pagerAdapter.setDatas(fragmentList)
                if (isOnlyRefreshTitle) return@Observer
                dataBinding.viewpager.adapter = pagerAdapter
                dataBinding.viewpager.offscreenPageLimit = 2
                dataBinding.tabLayout.setupWithViewPager(dataBinding.viewpager)
                dataBinding.tabLayout.addOnTabSelectedListener(getTabSelectedListener())
                dataBinding.viewpager.currentItem = 0
            }
        })
    }

    private fun initListener() {
        dataBinding.imgBack.setOnClickListener(this)
        dataBinding.imgTipClose.setOnClickListener(this)
        dataBinding.ivCustomerService.setOnClickListener(this)
    }

    private fun getTabSelectedListener() = object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            //Tab选中的样式
            setTab(tab)
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {         //非选中时的样式
            tab?.customView = null
        }

        override fun onTabReselected(p0: TabLayout.Tab?) {}
    }

    fun setTab(tab: TabLayout.Tab?) {
        val textView = TextView(this)
        //字体样式
        val selectedSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 16f, resources.displayMetrics)
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedSize)
        textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD) //加粗
        textView.gravity = Gravity.CENTER
        // 选中的字体颜色
        textView.setTextColor(ContextCompat.getColor(this, R.color.color_D53))
        textView.text = tab!!.text
        tab.customView = textView
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.img_back -> {
                finish()
            }
            R.id.img_tip_close -> {
                SpUtils.putBoolean(this, Constants.KEY_GOODS_MANAGER_TIP_IS_CLOSE, true)
                dataBinding.llGoodsManagerTip.visibility = View.GONE
            }
            R.id.iv_customer_service -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    ARouterUtils.jump(ActivityRouter.MINE_CENTER.CUSTOMER_SERVICE, this)
                }
            }
        }
    }

    var isOnlyRefreshTitle = false

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        when (messageBus.codeType) {
            MessageBus.msgId_refresh_goods_manager -> {
                isOnlyRefreshTitle = true
                viewModel.reqGoodsNumStatistics(SpUtils.getInstance().currentWineryInfo.dealerCode)
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}